#include "albumcover.h"
#include <QGridLayout>
#include <QTextEdit>
#include <QWebFrame>
#include <QMouseEvent>
#include <QWebElement>

extern "C" {
#include "sandcat.h"
}

AlbumCover::AlbumCover(QWidget *parent) :
    QWidget(parent)
{
    temporaryView = NULL;
    showBigCover = NULL;

    QGridLayout *coverLayout = new QGridLayout(this);
    coverLayout->setSpacing(0);
    coverLayout->setContentsMargins(0, 0, 0, 0);
    view = new QWebView(this);
    coverLayout->addWidget(view);

    view->installEventFilter(this);
}

AlbumCover::~AlbumCover()
{
}

void AlbumCover::refresh()
{
    if( STATUS_now_playing() == NULL ){
        return;
    }

    if( musicFileName != tr( ENTRY_name(STATUS_now_playing()) ) )
    {
        musicFileName = tr( ENTRY_name(STATUS_now_playing()) );
        if( ENTRY_artist(STATUS_now_playing()) && ENTRY_album(STATUS_now_playing()) )
        {
            google.clear();
            QString url("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&as_sitesearch=music.douban.com");
            url += tr("&q=") + tr( ENTRY_artist(STATUS_now_playing()) ) + tr(" ") + tr( ENTRY_album(STATUS_now_playing()) );
            google = QUrl(url);
        }else return;
    }else return;

    if(temporaryView)
        delete temporaryView;
    coverUrls.clear();
    temporaryView = new QWebView(this);
    temporaryView->load(google);
    connect(temporaryView, SIGNAL(loadFinished(bool)), this, SLOT(display(bool)));

}

void AlbumCover::display(bool bo)
{
    if( ! bo )
        return;

    QString string( temporaryView->page()->mainFrame()->toHtml() );

    QStringList sl = string.split(QChar(','));

    QStringList::Iterator i = sl.begin();
    for( ; i != sl.end(); i++)
    {
        QStringList sl1 = (*i).split(QChar(':'));
        if( sl1.at(0) == tr("\"url\"") )
        {
            QString url(sl1.at(1) + ":" + sl1.at(2));
            url.remove(0,1);
            url.remove(url.size()-1, 1);
            coverUrls.append( url );
            qDebug("%s", coverUrls.last().toUtf8().data());

        }
    }

    if(coverUrls.isEmpty()){
        return;
    }
    view->load(QUrl(coverUrls.at(0)));
    view->show();
}

bool AlbumCover::eventFilter(QObject *o, QEvent *e)
{
    if(o == view)
    {
        if(e->type() == QEvent::MouseButtonRelease || e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonDblClick)
        {
            if(showBigCover){
                delete showBigCover;
                showBigCover = 0;
            }
            if(coverUrls.isEmpty()) return true;
            showBigCover = new QWebView(0);
            showBigCover->setGeometry(0,0,500,500);
            showBigCover->load(QUrl(coverUrls.at(0)));
            showBigCover->show();
            return true;
        }

        return false;
    }
    else
    {
        return QWidget::eventFilter(o, e);
    }
}
